package com.example.zhuyu.basemvp.utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Objects;

import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

import static com.example.zhuyu.basemvp.utils.StreamUtil.bodyToString;

/**
 * @author zhuyu
 * @desc 打印网络拦截器中日志
 * @date 2018/8/28
 */
public class PrintNetLog {
    /**
     * 打印请求参数和请求url
     *
     * @param request 请求体
     */
    public void printRequestUrl(Request request) {
        if (request.body() != null && "json".equals(Objects.requireNonNull(Objects.requireNonNull(request.body()).contentType()).subtype())) {
            String paramsStr = bodyToString(request.body());
            LogUtil.e("请求地址: \n  " + request.url().toString() + "  请求参数:\n " + paramsStr);
        }
    }

    /**
     * 打印拼接后参数
     *
     * @param request 请求体
     */
    public void printParamsAfter(Request request) {
        if (request.body() != null && "json".equals(Objects.requireNonNull(Objects.requireNonNull(request.body()).contentType()).subtype())) {
            LogUtil.e("最终请求URL地址: \n" + request.url().toString()
                    + "  拼接后的参数: \n" + bodyToString(Objects.requireNonNull(request.body())));
        }
    }

    /**
     * 打印服务器返回结果
     *
     * @param response 响应结果
     */
    public void printServerResult(Response response) {
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            if (Objects.requireNonNull(responseBody.contentType()).subtype().equals("json")) {
                LogUtil.e("服务器返回的response: " + response.toString());
                long contentLength = responseBody.contentLength();
                try {
                    BufferedSource source = responseBody.source();
                    Buffer buffer = source.buffer();
                    source.request(Integer.MAX_VALUE); // Buffer the entire body.
                    if (contentLength != 0) {
                        LogUtil.e("服务器返回数据：\n" + buffer.clone().readString(Charset.forName("UTF-8")));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
